package com.antdesignbackend.backend.controller;

import com.alibaba.fastjson.JSONObject;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.Button;
import com.antdesignbackend.backend.entity.Menu;
import com.antdesignbackend.backend.entity.RoleMenu;
import com.antdesignbackend.backend.entity.entityVo.MenuVo;
import com.antdesignbackend.backend.entity.entityVo.RoleButtonVo;
import com.antdesignbackend.backend.entity.entityVo.RoleMenuVo;
import com.antdesignbackend.backend.service.ButtonService;
import com.antdesignbackend.backend.service.MenuService;
import com.antdesignbackend.backend.service.RoleButtonService;
import com.antdesignbackend.backend.service.RoleMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/menuManage")
public class menuController {
    @Autowired
    ButtonService buttonService;

    @Autowired
    RoleMenuService roleMenuService;
    @Autowired
    RoleButtonService roleButtonService;
    @Autowired
    MenuService menuService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/index")
    @AuthToken
    public String menuIndex() {
        return "menu/menuIndex";
    }

    /**
     * 处理点击菜单查询结果返回
     *
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    @AuthToken
    public ReturnVO menuList(@RequestBody RoleMenuVo roleMenuVo) {
        try {
            Map<String, Object> map = new HashMap<>();
            //得到角色与菜单多相关内容
            QueryWrapper<RoleMenuVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("rm.RoleID", roleMenuVo.getRoleIds()).eq("m.id", roleMenuVo.getId());
            List<RoleMenuVo> roleMenuVos = roleMenuService.selectRoleMenuList(queryWrapper, null);
            map.put("RoleMenu", roleMenuVos);
            //得到角色与功能相关内容
            if (!roleMenuVo.getLevel().equals("1")) {
                QueryWrapper<RoleButtonVo> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("menuID", roleMenuVo.getId()).eq("rb.RoleID", roleMenuVo.getRoleIds()).eq("activity", 1);
                List<RoleButtonVo> roleButtonVos = roleButtonService.selectRoleButtonList(queryWrapper1, null);
                map.put("RoleButton", roleButtonVos);
            }
            ReturnVO returnVO = new ReturnVO();
            returnVO.setCode("200");
            returnVO.setData(map);

            return returnVO;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }

    }

    /**
     * 右侧功能提交
     *
     * @return
     */
    @PostMapping("/menuRightSubmit")
    @ResponseBody
    @AuthToken
    public ReturnVO menuRightSubmit(@RequestBody MenuVo menuVo) {
        try {
            Menu menu = menuVo.getMenu();
            menuService.updateById(menu);

            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuID(menu.getId());
            roleMenu.setRoleID(menuVo.getRoleID());
            roleMenu.setActivity(menuVo.getActivity());
            QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("roleID", menuVo.getRoleID()).eq("menuID", menu.getId());
            roleMenuService.update(roleMenu, queryWrapper);
            //更新button
            List<Button> buttons = menuVo.getButtons();

            QueryWrapper<Button> buttonQueryWrapper = new QueryWrapper<>();
            buttons.forEach(b -> {
                Button button = new Button();
                button.setId(b.getId());
                button.setActivity(b.getActivity());
                button.setMenuName(menu.getTextCH());

                buttonQueryWrapper.eq("id", b.getId());
                buttonService.update(button, buttonQueryWrapper);
            });
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }

    }

    /**
     * 更新左侧菜单
     * 更新父节点归属及排序
     * 更新子节点归属及排序
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/menuLeftEdit")
    @ResponseBody
    @AuthToken
    public ReturnVO menuLeftEdit(@RequestBody JSONObject jsonObject) {
        String source = jsonObject.get("source").toString();
        List<MenuVo> menuVos = JSONObject.parseArray(source, MenuVo.class);

        //查询数据库中菜单表记录
        List<Menu> list = menuService.list();

        for (int i = 0; i < menuVos.size(); i++) {
            MenuVo mv = menuVos.get(i);
            Integer parentID = mv.getId();
            //更新叶子
            if (mv.getChildren() != null) {
                List<MenuVo> children = mv.getChildren();
                for (int j = 0; j < children.size(); j++) {
                    MenuVo mvChild = children.get(j);
                    int index = j;
                    //如果与数据库一致，就不更新
                    List<Menu> collect = list.stream().filter(f -> f.getId() == mvChild.getId()).
                            filter(f1 -> f1.getParentID() != parentID || f1.getOrderID() != index + 1).collect(Collectors.toList());
                    if (collect.size() > 0) {//存在不一致的记录
                        Menu menu = new Menu();
                        menu.setOrderID(index + 1);
                        menu.setParentID(parentID);
                        menu.setLevel("2");
                        UpdateWrapper<Menu> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", mvChild.getId());
                        menuService.update(menu, updateWrapper);
                    }
                }
            } else {
                //更新父节点
                int index = i;
                //如果与数据库一致，就不更新
                List<Menu> collect = list.stream().filter(f -> f.getId() == mv.getId() && f.getOrderID() != index + 1).collect(Collectors.toList());
                if (collect.size() > 0) { //存在不一致的记录
                    Menu menu = new Menu();
                    menu.setOrderID(index + 1);
                    menu.setParentID(0);
                    menu.setLevel("1");
                    UpdateWrapper<Menu> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", mv.getId());
                    menuService.update(menu, updateWrapper);
                }
            }
        }
        return new ReturnVO();
    }

    /**
     * 根据角色id查询菜单，允许一个用户多个角色
     */
    @PostMapping("/menu")
    @ResponseBody
    @AuthToken
    public ReturnVO menu(@RequestBody RoleMenuVo roleMenuVo) {
        ReturnVO returnVO = new ReturnVO();
        if (roleMenuVo != null) {
            QueryWrapper<RoleMenuVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("rm.RoleID", roleMenuVo.getRoleIds());
            List<RoleMenuVo> roleMenuVos = roleMenuService.selectRoleMenuList(queryWrapper, null);

            if (roleMenuVos.size() > 0) {
                returnVO.setCode("200");
                returnVO.setData(roleMenuVos);
            } else
                returnVO.setCode("503");
        } else {
            returnVO.setCode("503");
        }

        return returnVO;
    }
}
